package com.ruoyi.web.controller.rhtx;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dj.domain.ExcelTable;
import com.ruoyi.dj.domain.Rhtxdj;
import com.ruoyi.dj.domain.vo.RhtxdjVo;
import com.ruoyi.dj.service.IExcelTableService;
import com.ruoyi.dj.service.IRhtxdjService;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 新建格Controller
 *
 * @author ruoyi
 * @date 2024-04-29
 */
@RestController
@RequestMapping("/rhtx/table")
public class ExcelTableController extends BaseController {
    @Autowired
    private IExcelTableService excelTableService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private IRhtxdjService rhtxdjService;

    /**
     * 查询新建格列表
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExcelTable excelTable) {
        startPage();
        List<ExcelTable> list = excelTableService.selectExcelTableList(excelTable);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:one')")
    @GetMapping(value = "/{id}")
    public AjaxResult one(@PathVariable("id") Long id) {
        return success(excelTableService.selectExcelTableOne(id));
    }

    /**
     * 导出新建格列表
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:export')")
    @Log(title = "新建格", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExcelTable excelTable) {
        List<ExcelTable> list = excelTableService.selectExcelTableList(excelTable);
        ExcelUtil<ExcelTable> util = new ExcelUtil<ExcelTable>(ExcelTable.class);
        util.exportExcel(response, list, "新建格数据");
    }

    /**
     * 获取新建格详细信息
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:query')")
    @GetMapping(value = "/dj")
    public AjaxResult getInfo(ExcelTable excelTable) {
        if (excelTable.getTableId() == null) {
            return error("请选择表格");
        }
        if (excelTable.getStartTime() == null || excelTable.getEndTime() == null) {
            return error("请选择时间范围");
        }
        ExcelTable excelTable1 = excelTableService.selectExcelTableByTableId(excelTable);
        RhtxdjVo rhtxdjVo = new RhtxdjVo();
        rhtxdjVo.setSzm(excelTable1.getSzm());
        rhtxdjVo.setTableId(excelTable1.getTableId());
        rhtxdjVo.setStartTime(excelTable.getStartTime());
        rhtxdjVo.setEndTime(excelTable.getEndTime());
        rhtxdjVo.setParentIds(excelTable.getParentIds());
        rhtxdjVo.setDeptIds(excelTable.getDeptIds());
        rhtxdjVo.setDictCodes(excelTable.getDictCodes());
        List<Rhtxdj> rhtxdjs = rhtxdjService.selectRhtxdjList(rhtxdjVo);
        List<Map<String, Object>> resultList = new ArrayList<>();

        for (SysDept dept : excelTable1.getDepts()) {
            Map<String, Object> resultMap = new HashMap<>();
            for (Field field : SysDept.class.getDeclaredFields()) {
                try {
                    field.setAccessible(true);
                    Object value = field.get(dept);
                    resultMap.put(field.getName(), value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            Map<String, List<Rhtxdj>> newArr = rhtxdjs.stream().filter(i -> i.getDeptId().equals(dept.getDeptId())).collect(Collectors.groupingBy(i -> {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                return sdf.format(i.getLrTime());
            }));
            resultMap.put("dj", newArr);
            resultList.add(resultMap);
        }
        Map<String, Object> obj = new HashMap<>();
        obj.put("isType", excelTable1.getIsType());
        obj.put("tableName", excelTable1.getTableName());
        obj.put("cssz", excelTable1.getCssz());
        obj.put("dept", resultList);
        return success(obj);
    }

    /**
     * 新增新建格
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:add')")
    @Log(title = "新建格", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ExcelTable excelTable) {
        SysDictType sysDictType = new SysDictType();
        sysDictType.setDictName(excelTable.getTableName());
        sysDictType.setDictType(excelTable.getSzm());
        sysDictType.setStatus("0");
        if (!dictTypeService.checkDictTypeUnique(sysDictType)) {
            return error("新增字典'" + sysDictType.getDictName() + "'失败，字典类型已存在");
        }
        excelTable.setCreateBy(getUsername());
        sysDictType.setCreateBy(getUsername());
        return toAjax(excelTableService.insertExcelTable(excelTable, sysDictType));
    }

    /**
     * 修改新建格
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:edit')")
    @Log(title = "新建格", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ExcelTable excelTable) {
        SysDictType sysDictType = new SysDictType();
        sysDictType.setDictName(excelTable.getTableName());
        sysDictType.setDictType(excelTable.getSzm());
        sysDictType.setStatus("0");
        excelTable.setUpdateBy(getUsername());
        sysDictType.setUpdateBy(getUsername());
        return toAjax(excelTableService.updateExcelTable(excelTable, sysDictType));
    }

    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:del')")
    @Log(title = "新建格", businessType = BusinessType.DELETE)
    @DeleteMapping("/del/{tableId}")
    public AjaxResult removeOne(@PathVariable Long tableId) {
        return toAjax(excelTableService.deleteExcelTableByTableId(tableId));
    }

    /**
     * 删除新建格
     */
    @PreAuthorize("@ss.hasPermi('qz-rhtx:table:remove')")
    @Log(title = "新建格", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tableIds}")
    public AjaxResult remove(@PathVariable Long[] tableIds) {
        return toAjax(excelTableService.deleteExcelTableByTableIds(tableIds));
    }
}